<template>
  <div class="mark-assignment">
    <h1>作业列表</h1>
    <table>
      <thead>
      <tr>
        <th>提交人</th>
        <th>作业名称</th>
        <th>提交时间</th>
        <th>分数</th>
        <th>评语</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="submission in submissions" :key="submission.id" class="table-row">
        <td>{{ submission.stu_id }}</td>
        <td>{{ homework.title }}</td>
        <td>{{ formatDate(submission.submit_at) }}</td>
        <td>
          <input type="number" v-model="submission.score" min="0" max="100" />
        </td>
        <td>
          <input type="text" v-model="submission.comment" placeholder="输入评语" />
        </td>
        <td>
          <button @click="downloadFile(submission)">查看</button>
          <button @click="saveAssignment(submission.submission_id)">保存</button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from 'axios';
import {BASE_URL} from "@/config";

export default {
  data() {
    return {
      submissions: [],
      homework:{}
    };
  },
  methods: {
    async fetchAssignments() {
      try {
        const id = this.$route.params.homework_id;
        const submissionresponse = await axios.post(`${BASE_URL}/homework/assign/getsubmissions` ,{homework_id: id} );
        const homeworkresponse = await axios.post(`${BASE_URL}/homework/showHomework`, { homework_id: id });
        this.submissions = submissionresponse.data.data; // 假设返回的格式为 { data: [...] }
        this.homework = homeworkresponse.data.data; // 假设返回的格式为 { data: [...] }
      } catch (error) {
        console.error('获取作业列表失败:', error);
      }
    },
    formatDate(date) {
      const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' };
      return new Date(date).toLocaleString('zh-CN', options);
    },
    markAssignment(id) {
      const submission = this.submissions.find(a => a.submission_id === id);
      if (submission) {
        submission.isEditing = true; // 显示评分和评语输入框
        console.log('标记作业ID:', id, '分数:', submission.score, '评语:', submission.comment);
      } else {
        console.error('未找到对应的作业:', id);
      }
    },
    async downloadFile(assignment) {
      try {
        // 发送 POST 请求
        const response = await axios.post(`${BASE_URL}/homework/downloadSub`, {
          stu_id: assignment.stu_id,
          homework_id: assignment.homework_id,
        });

        // 假设后端返回的数据是 Base64 格式
        const base64Data = response.data.data.content; // 确保 data 是 Base64 字符串
        const mimeType = "application/pdf"; // 设置文件的 MIME 类型
        const blob = this.base64ToBlob(base64Data, mimeType);
        const name = response.data.data.fileName;

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;

        // 设置文件名
        link.setAttribute("download", `${name}`);
        document.body.appendChild(link);
        link.click();

        // 清理资源
        link.remove();
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error("文件下载失败:", error);
        this.$message.error("文件下载失败");
      }
    },

    // Base64 转 Blob 工具函数
    base64ToBlob(base64, mimeType) {
      const byteCharacters = atob(base64); // 解码 Base64
      const byteNumbers = new Array(byteCharacters.length)
          .fill(0)
          .map((_, i) => byteCharacters.charCodeAt(i));
      const byteArray = new Uint8Array(byteNumbers);
      return new Blob([byteArray], { type: mimeType });
    },
    // 保存评分和评语
    async saveAssignment(id) {
      const submission = this.submissions.find(a => a.submission_id === id);
      if (!submission) {
        alert('作业未找到，请重试。');
        return;
      }

      try {
        const requestData = {
          submission_id: submission.submission_id,
          score: submission.score,
          comment: submission.comment,
        };

        // 使用 POST 方法并且确保路径匹配后端接口
        const response = await axios.post(`${BASE_URL}/homework/assign/submission/scoreAndComment`, requestData);

        if (response.data && response.data.code === 200) {
          alert('保存成功！');
          submission.isEditing = false; // 隐藏评分和评语输入框
        } else {
          console.error('保存失败:', response.data.message);
          alert('保存失败，请重试。');
        }
      } catch (error) {
        console.error('保存作业失败:', error);
        alert('保存失败，请重试。');
      }
    },
  },
  mounted() {
    this.fetchAssignments();
  }
};
</script>

<style scoped>
.mark-assignment {
  padding: 20px;
  font-family: 'Arial', sans-serif;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h1 {
  color: #333;
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ccc;
  padding: 12px;
  text-align: left;
  transition: background-color 0.3s;
}

th {
  background-color: #3f51b5;
  color: white;
}

tbody tr:nth-child(even) {
  background-color: #f2f2f2;
}

tbody tr:hover {
  background-color: #e0e7ff;
}

td input[type="number"],
td input[type="text"] {
  width: 90%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}

td input[type="number"]:focus,
td input[type="text"]:focus {
  outline: none;
  border-color: #3f51b5;
  box-shadow: 0 0 5px rgba(63, 81, 181, 0.5);
}

button {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  background-color: #3f51b5;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.2s;
  margin: 0 5px 0 0; /* 将左边距设为5px，去掉右边距 */
}

button:last-child {
  margin-right: 0; /* 最后一个按钮不留右边距 */
}

button:hover {
  background-color: #2c387e;
  transform: scale(1.05);
}
</style>
